extends RefCounted
class_name BuffState

var data: BuffData
## 施加者，可为空
var user: Node                      
## 被作用对象（角色）
var holder: Node                      
## 保持时间
var remaining: float
## 当前层数
var stacks: int = 1
## tick时间
var tick_timer: float = 0.0

func _init(buff_data: BuffData, _holder: Node, _user: Node = null): 
	data = buff_data
	holder = _holder
	user = _user
	remaining = buff_data.get_duration()
	tick_timer = 0.0

func advance(delta: float) -> void:
	## -1及以下不触发
	if data.get_tick_interval() <= -1:
		return
	if data.get_duration() > 0.0:
		remaining -= delta
	if data.get_tick_interval() > 0.0:
		tick_timer += delta
		while tick_timer >= data.get_tick_interval():   # 可能一次跳多帧
			tick_timer -= data.get_tick_interval()
			_exec_script(data.get_buff_script(), "on_tick")

func expired() -> bool:
	## -1即以下等于永动buff
	if data.get_duration() <= -1:
		return false
	return data.get_duration() > 0.0 and remaining <= 0.0

func _exec_script(scr: Buff, fn: String) -> void:
	if scr and scr.has_method(fn):
		scr.call(fn, self)   # 传 BuffState 自身

## 获取剩余时间百分比
func get_remaining_percentage() -> float:
	if data.get_duration() <= 0.0:
		return 1.0
	return remaining / data.get_duration()

## 检查是否可以叠加
func can_stack() -> bool:
	return stacks < data.get_max_stacks()

## 增加层数
func add_stack() -> void:
	if can_stack():
		stacks += 1

## 获取当前层数
func get_stacks() -> int:
	return stacks
